package com.eningqu.aipen.ui.home.book;


import static com.luck.picture.lib.config.PictureSelectionConfig.selectorStyle;
import static com.luck.picture.lib.config.PictureSelectionConfig.videoPlayerEngine;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.eningqu.aipen.demo.R;
import com.eningqu.aipen.demo.databinding.ActivityFormBinding;
import com.eningqu.aipen.logic.model.ResponseBean;
import com.eningqu.aipen.logic.model.medical.GhSingleBean;
import com.eningqu.aipen.logic.model.medical.MedicalNode;
import com.eningqu.aipen.logic.network.Apis;
import com.eningqu.aipen.logic.network.BaseRetrofitUtils;
import com.eningqu.aipen.logic.network.ChatRetrofitUtils;
import com.eningqu.aipen.logic.network.SchedulerTransformer;
import com.eningqu.aipen.ui.adapter.GridImageAdapter;
import com.eningqu.aipen.ui.base.BaseActivity;
import com.eningqu.aipen.utils.GlideEngine;
import com.eningqu.aipen.utils.GlobalConfig;
import com.eningqu.aipen.utils.PopTipUtils;
import com.eningqu.aipen.utils.SPUtil;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.FullScreenDialog;
import com.kongzue.dialogx.dialogs.PopMenu;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.entity.MediaExtraInfo;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.language.LanguageConfig;
import com.luck.picture.lib.utils.DateUtils;
import com.luck.picture.lib.utils.MediaUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;
import top.zibin.luban.OnRenameListener;

/**
 * Package:com.eningqu.aipen.ui.home.book
 * Author:starr
 * Time:2023/11/13 11:16
 * Description: 手写识别出的文字表单
 */
public class FormActivity extends BaseActivity<ActivityFormBinding> {

    private static HashMap<String, Bitmap> bitmapMap = null;
    private static HashMap<String, String> bitmapBase64 = new HashMap<>();

    private static Integer blId;
    private static Integer ghId;
    private static Integer hzId;
    private static Integer ysId;

    private static Handler handler;

    //病历模板信息
    private final MedicalNode medicalNode = new MedicalNode();

    //图片选择适配器
    private GridImageAdapter imageAdapter;
    private static ArrayList<LocalMedia> mData = new ArrayList<LocalMedia>();
    private RecyclerView recyclerView;

    //电子病历图片原件
    private static Bitmap bitmap;

    public static void startAction(Context context, Bundle bundle) {
        Intent intent = new Intent(context, FormActivity.class);
        bitmap = bundle.getParcelable("image");
        blId = bundle.getInt("blId");
        ghId = bundle.getInt("ghId");
        hzId = bundle.getInt("hzId");
        bitmapMap = (HashMap<String, Bitmap>) bundle.getSerializable("images");
        mData = bundle.getParcelableArrayList("pictures");
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_form;
    }

    @Override
    protected void initView() {
        handler = new Handler();
        mBinding.setClick(new FormClick());
        recyclerView = mBinding.rvAddPic;
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
    }

    @Override
    protected void initData() {
        ysId = (Integer) SPUtil.getInstance().getData(GlobalConfig.ysId, -1);
        if (ysId == -1) {
            ToastUtils.showShort("请先登录....");
        } else {
            medicalNode.emrBlId = blId;
            medicalNode.emrJdPage = 10;
            medicalNode.emrJdTypeId = 0;//西医病历
            medicalNode.modelEntity.emrXyBefore = "测试数据：从手写病历中识别出的既往史，从手写病历中识别出的既往史，从手写病历中识别出的既往史，从手写病历中识别出的既往史";
            @SuppressLint("SimpleDateFormat") SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            medicalNode.modelEntity.emrXyDate = spf.format(new Date());
            medicalNode.modelEntity.emrXyMain = "测试数据：从手写病历中识别出的主诉，从手写病历中识别出的主诉，从手写病历中识别出的主诉，从手写病历中识别出的主诉";
            medicalNode.modelEntity.emrXyKs = "内科";
            medicalNode.modelEntity.emrXyDeal = "测试数据：从手写病历中识别出的处理及建议，从手写病历中识别出的处理及建议，从手写病历中识别出的处理及建议，从手写病历中识别出的处理及建议";
            medicalNode.modelEntity.emrYsName = (String) SPUtil.getInstance().getData(GlobalConfig.ysName, "医生名字");
            medicalNode.modelEntity.emrXyCheck = "从手写病历中识别出的检查资料";
            medicalNode.modelEntity.emrYsId = ysId;
            medicalNode.modelEntity.emrXyNow = "测试数据：从手写病历中识别出的现病史，从手写病历中识别出的现病史，从手写病历中识别出的现病史，从手写病历中识别出的现病史";
        }

        new Thread(() -> {
            try {
                bitmapBase64 = getBitmapsASBase64(bitmapMap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        imageAdapter = new GridImageAdapter(getContext(), mData);
        imageAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                //预览图片
                PictureSelector.create(getContext())
                        .openPreview()
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setVideoPlayerEngine(videoPlayerEngine)
                        .setSelectorUIStyle(selectorStyle)
                        .setLanguage(LanguageConfig.UNKNOWN_LANGUAGE)
                        .isPreviewZoomEffect(false, recyclerView)
                        .startActivityPreview(position, true, imageAdapter.getData());
            }

            @Override
            public void openPicture() {
                //打开弹窗
                openDialogWindow();
            }
        });
        recyclerView.setAdapter(imageAdapter);
    }

    @SuppressLint({"CheckResult", "SetTextI18n"})
    @Override
    protected void async() {
        BaseRetrofitUtils.getInstance().create(Apis.class).getHzInfo(hzId)
                .compose(new SchedulerTransformer<>())
                .subscribe(bean -> {
                    mBinding.tvName.setText(bean.emrHzInfo.emrHzName);
                    mBinding.tvAge.setText(bean.emrHzInfo.emrHzAge.toString());
                    mBinding.tvSex.setText(bean.emrHzInfo.emrHzSex);
                });
        if (ysId != -1) {
            BaseRetrofitUtils.getInstance().create(Apis.class).getDoctorInfo(ysId)
                    .compose(new SchedulerTransformer<>())
                    .subscribe(bean -> {
                        mBinding.tvKs.setText(bean.emrYsInfo.emrYsSection);
                    });
        }

        //手写识别
        writeNet();
    }

    private void openDialogWindow() {
        CustomDialog.build()
                .setMaskColor(Color.parseColor("#aaEDEDED"))
                .setCustomView(new OnBindView<CustomDialog>(R.layout.dialog_add_pic) {
                    @Override
                    public void onBind(CustomDialog dialog, View view) {
                        Button btOk = view.findViewById(R.id.btn_cancel);
                        TextView btnTakePic = view.findViewById(R.id.take_pic);
                        TextView btnFromNoun = view.findViewById(R.id.from_noun);
                        btOk.setOnClickListener(v -> dialog.dismiss());
                        btnTakePic.setOnClickListener(v -> {
                            //拍照
                            takePicture();
                            dialog.dismiss();
                        });
                        btnFromNoun.setOnClickListener(v -> {
                            //如果选了图片，那就不能再选视频了，避免出现一个动态同时发布图片和视频素材
                            if (imageAdapter.getData().size() != 0) {
                                selectFromNoun(SelectMimeType.ofImage());
                            } else {
                                selectFromNoun(SelectMimeType.ofAll());
                            }
                            dialog.dismiss();
                        });
                    }
                })
                .show();
    }

    //调用相机拍照
    private void takePicture() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofImage())
                .setCompressEngine(new ImageFileCompressEngine())//设置压缩图片引擎
                .setSelectedData(imageAdapter.getData())//已经选中的图片
                .forResultActivity(PictureConfig.REQUEST_CAMERA);
    }

    /**
     * 从相册选择图片或视频
     * forResult设置返回码，后续处理逻辑详看 onActivityResult
     */
    private void selectFromNoun(int type) {
        PictureSelector.create(this)
                .openGallery(type)
                .setCompressEngine(new ImageFileCompressEngine())//设置压缩图片引擎
                .setImageEngine(GlideEngine.createGlideEngine())
                .setSelectedData(imageAdapter.getData())//已经选中的图片
                .setMaxSelectNum(3)
                .setMinVideoSelectNum(1)
                .setMaxVideoSelectNum(1)
                .isPreviewVideo(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);//设置返回码
    }

    /**
     * 自定义压缩
     */
    private static class ImageFileCompressEngine implements CompressFileEngine {
        @Override
        public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
            Luban.with(context).load(source).ignoreBy(100).setRenameListener(new OnRenameListener() {
                @Override
                public String rename(String filePath) {
                    int indexOf = filePath.lastIndexOf(".");
                    String postfix = indexOf != -1 ? filePath.substring(indexOf) : ".jpg";
                    return DateUtils.getCreateFileName("CMP_") + postfix;
                }
            }).filter(path -> {
                if (PictureMimeType.isUrlHasImage(path) && !PictureMimeType.isHasHttp(path)) {
                    return true;
                }
                return !PictureMimeType.isUrlHasGif(path);
            }).setCompressListener(new OnNewCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(String source, File compressFile) {
                    if (call != null) {
                        call.onCallback(source, compressFile.getAbsolutePath());
                    }
                }

                @Override
                public void onError(String source, Throwable e) {
                    if (call != null) {
                        call.onCallback(source, null);
                    }
                }
            }).launch();
        }
    }

    //回调，获取用户选择的图片
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                case PictureConfig.REQUEST_CAMERA: {
                    //保存选中的照片
                    mData = PictureSelector.obtainSelectorList(data);
                    analyticalSelectResults(mData);
                }
                break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            PopTip.tip("选择图片回调失败");
        }
    }

    private void analyticalSelectResults(List<LocalMedia> result) {
        for (LocalMedia media : result) {
            if (media.getWidth() == 0 || media.getHeight() == 0) {
                if (PictureMimeType.isHasImage(media.getMimeType())) {
                    MediaExtraInfo info = MediaUtils.getImageSize(this, media.getPath());
                    media.setWidth(info.getWidth());
                    media.setHeight(info.getHeight());
                } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                    MediaExtraInfo info = MediaUtils.getVideoSize(this, media.getPath());
                    media.setWidth(info.getWidth());
                    media.setHeight(info.getHeight());
                }
            }
        }

        runOnUiThread(() -> {
            boolean isMaxSize = result.size() == imageAdapter.getSelectMax();
            int oldSize = imageAdapter.getData().size();
            imageAdapter.notifyItemRangeRemoved(0, (isMaxSize ? oldSize + 1 : oldSize));
            imageAdapter.getData().clear();
            imageAdapter.getData().addAll(result);
            imageAdapter.notifyItemRangeInserted(0, result.size());
        });

    }

    public File bitmapToFile(Bitmap bitmap, String filename) {
        File filesDir = getContext().getFilesDir();
        File imageFile = new File(filesDir, filename + ".png");

        OutputStream os;
        try {
            os = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imageFile;
    }


    @SuppressWarnings("all")
    public class FormClick {

        //测试：多文件上传
        public void uploadMultiFile(View view) {

        }

        //测试：单文件上传
        //将病历本的原件上传至后台
        public void uploadSingleFile(View view) {
            File imageFile = bitmapToFile(bitmap, "imageFileName");
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
            MultipartBody.Part body = MultipartBody.Part.createFormData("file", imageFile.getName(), requestFile);
            BaseRetrofitUtils.getInstance().create(Apis.class).uploadAliyun(body)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<ResponseBean>() {
                        @Override
                        public void accept(ResponseBean responseBean) throws Exception {
                            PopTip.tip(responseBean.msg);
                        }
                    });
        }

        public void chooseType(View view) {

        }

        public void chooseKs(View view) {
            mBinding.tvKs.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PopMenu.show(v, new String[]{"外科", "内科", "呼吸科", "其他"})
                            .setOnMenuItemClickListener(new OnMenuItemClickListener<PopMenu>() {
                                @Override
                                public boolean onClick(PopMenu popMenu, CharSequence text, int i) {
                                    mBinding.tvKs.setText(text);
                                    return false;
                                }
                            });
                }
            });
        }

        public void change(View view) {
            ToastUtils.showShort("切换成电子版病历单");
            loadDialog();
        }

        public void back(View view) {
            finish();
        }


        public void saveRx(View view) {

            medicalNode.modelEntity.emrXyBefore = mBinding.etBefore.getText().toString();
            medicalNode.modelEntity.emrXyNow = mBinding.etNow.getText().toString();
            medicalNode.modelEntity.emrXyCheck = mBinding.etCheck.getText().toString();
            medicalNode.modelEntity.emrXyDeal = mBinding.etDeal.getText().toString();
            medicalNode.modelEntity.emrXyMain = mBinding.etAction.getText().toString();


            if (mData != null && !mData.isEmpty()) {

                //保存多张图片
                //1.多图片上传
                //2.单图片上传
                //3.保存
                MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                for (LocalMedia media : mData) {
                    if(media.getCompressPath()!=null){
                        File file = new File(media.getCompressPath());
                        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        builder.addFormDataPart("files", file.getName(), requestBody);
                    }
                }
                List<MultipartBody.Part> parts = builder.build().parts();
                BaseRetrofitUtils.getInstance().create(Apis.class).uploagAliyunImgs(parts)
                        .subscribeOn(Schedulers.io())
                        .flatMap(new Function<ResponseBean, ObservableSource<ResponseBean>>() {
                            @Override
                            public ObservableSource<ResponseBean> apply(ResponseBean response) throws Exception {
                                medicalNode.modelEntity.emrXyImgs = response.msg;
                                File imageFile = bitmapToFile(bitmap, "imageFileName");
                                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
                                MultipartBody.Part body = MultipartBody.Part.createFormData("file", imageFile.getName(), requestFile);
                                return BaseRetrofitUtils.getInstance().create(Apis.class).uploadAliyun(body);
                            }
                        })
                        .flatMap(new Function<ResponseBean, ObservableSource<ResponseBean>>() {
                            @Override
                            public ObservableSource<ResponseBean> apply(ResponseBean responseBean) throws Exception {
                                medicalNode.modelEntity.emrXyImg = responseBean.msg;
                                return BaseRetrofitUtils.getInstance().create(Apis.class).saveMedicalNode(medicalNode);
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<ResponseBean>() {
                            @Override
                            public void accept(ResponseBean responseBean) throws Exception {
                                if (responseBean.msg.equals("success")) {
                                    BaseRetrofitUtils.getInstance().create(Apis.class).updateTime(blId, medicalNode.modelEntity.emrXyDate)
                                            .compose(new SchedulerTransformer<>())
                                            .subscribe(update -> {
                                                if(update.msg.equals("success")){
                                                    PopTipUtils.successMsg("病历信息已更新");
                                                    //更新挂号状态
                                                    if (ghId != null) {
                                                        BaseRetrofitUtils.getInstance().create(Apis.class).getGhInfo(ghId)
                                                                .subscribeOn(Schedulers.io())
                                                                .flatMap(new Function<GhSingleBean, ObservableSource<ResponseBean>>() {
                                                                    @Override
                                                                    public ObservableSource<ResponseBean> apply(GhSingleBean ghSingleBean) throws Exception {
                                                                        ghSingleBean.emrGhInfo.emrGhState = 1;
                                                                        return BaseRetrofitUtils.getInstance().create(Apis.class).updateGhInfo(ghSingleBean.emrGhInfo);
                                                                    }
                                                                })
                                                                .observeOn(AndroidSchedulers.mainThread())
                                                                .subscribe(new Consumer<ResponseBean>() {
                                                                    @Override
                                                                    public void accept(ResponseBean responseBean) throws Exception {
                                                                        if(responseBean.msg.equals("success")){
                                                                            PopTipUtils.successMsg("挂号状态已更新");
                                                                        }else{
                                                                            PopTipUtils.errMsg("挂号状态更新失败");
                                                                        }
                                                                    }
                                                                });
                                                    }
                                                }
                                            });
                                }else{
                                    PopTipUtils.errMsg("病历信息更新失败"+responseBean.msg);
                                }
                            }
                        });

            } else {
                //2.保存单张图片
                File imageFile = bitmapToFile(bitmap, "imageFileName");
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
                MultipartBody.Part body = MultipartBody.Part.createFormData("file", imageFile.getName(), requestFile);
                BaseRetrofitUtils.getInstance().create(Apis.class).uploadAliyun(body)
                        .subscribeOn(Schedulers.io())
                        .flatMap(new Function<ResponseBean, ObservableSource<ResponseBean>>() {
                            @Override
                            public ObservableSource<ResponseBean> apply(ResponseBean responseBean) throws Exception {
                                medicalNode.modelEntity.emrXyImg = responseBean.msg;
                                return BaseRetrofitUtils.getInstance().create(Apis.class).saveMedicalNode(medicalNode);
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<ResponseBean>() {
                            @Override
                            public void accept(ResponseBean responseBean) throws Exception {
                                if (responseBean.msg.equals("success")) {
                                    BaseRetrofitUtils.getInstance().create(Apis.class).updateTime(blId, medicalNode.modelEntity.emrXyDate)
                                            .compose(new SchedulerTransformer<>())
                                            .subscribe(update -> {
                                                if(update.msg.equals("success")){
                                                    PopTipUtils.successMsg("病历信息已更新");
                                                    //更新挂号状态
                                                    if (ghId != null) {
                                                        BaseRetrofitUtils.getInstance().create(Apis.class).getGhInfo(ghId)
                                                                .subscribeOn(Schedulers.io())
                                                                .flatMap(new Function<GhSingleBean, ObservableSource<ResponseBean>>() {
                                                                    @Override
                                                                    public ObservableSource<ResponseBean> apply(GhSingleBean ghSingleBean) throws Exception {
                                                                        ghSingleBean.emrGhInfo.emrGhState = 1;
                                                                        return BaseRetrofitUtils.getInstance().create(Apis.class).updateGhInfo(ghSingleBean.emrGhInfo);
                                                                    }
                                                                })
                                                                .observeOn(AndroidSchedulers.mainThread())
                                                                .subscribe(new Consumer<ResponseBean>() {
                                                                    @Override
                                                                    public void accept(ResponseBean responseBean) throws Exception {
                                                                        if(responseBean.msg.equals("success")){
                                                                            PopTipUtils.successMsg("挂号状态已更新");
                                                                        }else{
                                                                            PopTipUtils.errMsg("挂号状态更新失败");
                                                                        }
                                                                    }
                                                                });
                                                    }
                                                }
                                            });
                                }else{
                                    PopTipUtils.errMsg("病历信息更新失败"+responseBean.msg);
                                }
                            }
                        });
            }


        }

        public void write(View view) {
            mBinding.etDeal.setText(medicalNode.modelEntity.emrXyDeal);
            mBinding.etCheck.setText(medicalNode.modelEntity.emrXyCheck);//检查资料
            mBinding.etBefore.setText(medicalNode.modelEntity.emrXyBefore);
            mBinding.etNow.setText(medicalNode.modelEntity.emrXyNow);
            mBinding.etAction.setText(medicalNode.modelEntity.emrXyMain);//主诉
        }


        //手写文字识别
        public void getWriteNet(View view) {
            writeNet();
        }
    }

    private void writeNet() {
        WaitDialog.show("正在识别手写病历");
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            WaitDialog.dismiss();
            TipDialog.show("病历识别成功", WaitDialog.TYPE.SUCCESS);
        }, 2000);


        getWriteToken("tem");
        getWriteToken("breath");
        getWriteToken("pulse");
        getWriteToken("press");
        getWriteToken("allergy");
        getWriteToken("main");
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getWriteToken("now");
                getWriteToken("before");
                getWriteToken("check");
                getWriteToken("first");
                getWriteToken("deal");
            }
        }, 1000);
    }

    public void loadDialog() {
        FullScreenDialog.show(new OnBindView<FullScreenDialog>(R.layout.dialog_change) {
            @Override
            public void onBind(FullScreenDialog customDialog, View view) {
                ImageView ivPic;
                ivPic = view.findViewById(R.id.iv_pic);
                Glide.with(ivPic)
                        .load(bitmap)
                        .placeholder(R.drawable.bg_word1)
                        .into(ivPic);
            }
        });
    }

    @SuppressLint("CheckResult")
    public void getWriteToken(String imageKey) {
        ChatRetrofitUtils.getInstance().create(Apis.class).getBaiduToken(
                GlobalConfig.write_client_key, GlobalConfig.write_secret_key,
                "client_credentials")
                .compose(new SchedulerTransformer<>())
                .subscribe(bean -> {
                    if (bean != null) {
                        String accessToken = bean.accessToken;
                        //分数
                        int origin;
                        //具体去手写
                        startWrite(accessToken, bitmapBase64.get(imageKey), imageKey);
                        //分数加减
                        //writeNode(null)  realNode
                        int result;

                    } else {
                        LogUtils.i("body为空");
                    }
                });
    }

    @SuppressWarnings("all")
    private void startWrite(String accessToken, String image, String imageKey) {
        // image 可以通过 getFileContentAsBase64("C:\fakepath\Android Gradle.png") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image=" + image +
                "&detect_direction=false&probability=false");
        ChatRetrofitUtils.getInstance().create(Apis.class).getWriteResult(body, accessToken)
                .compose(new SchedulerTransformer<>())
                .subscribe(bean -> {
                    if (bean.wordsResult == null || bean.wordsResult.size() <= 0) {
                        runOnUiThread(() -> LogUtils.i("未识别到字体"));
                    } else {
                        StringBuilder words = new StringBuilder();
                        for (int i = 0; i < bean.wordsResult.size(); ++i) {
                            words.append(bean.wordsResult.get(i).words);
                        }
                        runOnUiThread(() -> {
                            switch (imageKey) {

                                case "tem": {
                                    medicalNode.modelEntity.emrXyTem = Integer.parseInt(words.toString());
                                    mBinding.tvTem.setText(words);
                                }
                                break;
                                case "breath": {
                                    medicalNode.modelEntity.emrXyBreath = Integer.parseInt(words.toString());
                                    mBinding.tvBreath.setText(words);
                                }
                                break;
                                case "pulse": {
                                    medicalNode.modelEntity.emrXyPluse = Integer.parseInt(words.toString());
                                    mBinding.tvPulse.setText(words);
                                }
                                break;
                                case "press": {
                                    medicalNode.modelEntity.emrXyPress = Integer.parseInt(words.toString());
                                    mBinding.tvPress.setText(words);
                                }
                                break;

                                case "main": {//主诉
                                    medicalNode.modelEntity.emrXyMain = words.toString();
                                    mBinding.etAction.setText(words);
                                }
                                break;
                                case "now": {//现病史
                                    medicalNode.modelEntity.emrXyNow = words.toString();
                                    mBinding.etNow.setText(words);
                                }
                                break;
                                case "before": {
                                    medicalNode.modelEntity.emrXyBefore = words.toString();
                                    mBinding.etBefore.setText(words);
                                }
                                break;
                                case "check": {
                                    medicalNode.modelEntity.emrXyCheck = words.toString();
                                    mBinding.etCheck.setText(words);
                                }
                                break;
                                case "first": {
                                    medicalNode.modelEntity.emrXyDeal = words.toString();
                                    mBinding.etFirst.setText(words);
                                }
                                break;
                                case "deal": {
                                    medicalNode.modelEntity.emrXyDeal = words.toString();
                                    mBinding.etDeal.setText(words);
                                }
                                break;
                            }
                            ToastUtils.showShort(words);
                        });
                    }
                });

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    String getFileContentAsBase64(Bitmap bitmap) throws IOException {
//        Bitmap bitmap= BitmapFactory.decodeResource(this.getResources(),R.drawable.write);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        String base64 = Base64.getEncoder().encodeToString(b);
        base64 = URLEncoder.encode(base64, "utf-8");
        return base64;
    }

    HashMap getBitmapsASBase64(HashMap<String, Bitmap> bitmapMap) throws IOException {

        bitmapBase64.put("tem", getFileContentAsBase64(bitmapMap.get("tem")));
        bitmapBase64.put("breath", getFileContentAsBase64(bitmapMap.get("breath")));
        bitmapBase64.put("pulse", getFileContentAsBase64(bitmapMap.get("pulse")));
        bitmapBase64.put("press", getFileContentAsBase64(bitmapMap.get("press")));

        bitmapBase64.put("allergy", getFileContentAsBase64(bitmapMap.get("allergy")));
        bitmapBase64.put("main", getFileContentAsBase64(bitmapMap.get("main")));
        bitmapBase64.put("now", getFileContentAsBase64(bitmapMap.get("now")));
        bitmapBase64.put("before", getFileContentAsBase64(bitmapMap.get("before")));
        bitmapBase64.put("check", getFileContentAsBase64(bitmapMap.get("check")));
        bitmapBase64.put("first", getFileContentAsBase64(bitmapMap.get("first")));
        bitmapBase64.put("deal", getFileContentAsBase64(bitmapMap.get("deal")));

        return bitmapBase64;
    }
}
